// server.js
const path = require('path')
const fs = require('fs')
const express = require('express')
const server = require('express')()
const { createBundleRenderer, vueServerRenderer } = require('vue-server-renderer')
const createApp = path.join(__dirname, './dist/script/server.bundle.js')
const template = fs.readFileSync(path.join(__dirname, './src/index.html'), 'utf8')
const serverBundle = require('./dist/vue-ssr-server-bundle.json')
const clientManifest = require('./dist/vue-ssr-client-manifest.json')

const config = {
  cdn: 'http://127.0.0.1:9000',
  success: '46B50148'
}

const renderer = createBundleRenderer(serverBundle, {
  runInNewContext: false,
  template: template,
  clientManifest: clientManifest
})

server.use(express.static('dist'));
server.get('*', (req, res) => {
  const context = {
    url: req.url,
    ...config
  }
  renderer.renderToString(context)
  .then(html => {
    res.end(html)
  })
  .catch(err => {

    if (err === 404) {
      res.status(404).end('Page not found')
    } else {
      res.status(500).end('Internal Server Error')
      console.log(err);
    }
  })
})

server.listen(9000)
